package cn.enine.tbcharge.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.LitePal;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.enine.tbcharge.R;
import cn.enine.tbcharge.adapter.CommonAdapter;
import cn.enine.tbcharge.adapter.ViewHolder;
import cn.enine.tbcharge.base.MyBaseActivity;
import cn.enine.tbcharge.pojo.AppSfMain;
import cn.enine.tbcharge.pojo.AppSfSub;
import cn.enine.tbcharge.pojo.RetMsg;
import cn.enine.tbcharge.util.DateConvert;
import cn.enine.tbcharge.util.HttpUrl;
import cn.enine.tbcharge.util.LvHeightUtil;
import cn.enine.tbcharge.util.MyApplication;
import cn.enine.tbcharge.util.MyToastUtil;
import cn.enine.tbcharge.util.NetWorkUtils;
import cn.enine.tbcharge.util.RegexUtils;
import cn.enine.tbcharge.util.SharedPreferencesUtils;
import cn.enine.tbcharge.util.StringUtils;
import cn.enine.tbcharge.util.UserClient;
import cn.enine.tbcharge.utils.AidlUtil;
import cn.enine.tbcharge.utils.BluetoothUtil;
import cn.enine.tbcharge.utils.BytesUtil;

public class SfaddActivity extends MyBaseActivity {
    Context con = SfaddActivity.this;
    AppSfMain obj;
    private TextView title, saveBtn, totalfy, mxadd, zhifu;
    private EditText name, idno, phone;
    LinearLayout back, zfll;
    boolean isadd = false;//是否是新添加
    String url = "";
    ListView listView;
    ZLoadingDialog dialog;//加载动画

    List<AppSfSub> list;
    private int pageNum1 = 1;// 无关键字页数
    private EditText key;
    private String mainid = "";

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_sfadd);
        listView = (ListView) findViewById(R.id.listView);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle b = new Bundle();
                Log.i("listsize",list.size()+"");
                b.putSerializable("b", list.get(i));
                startActivity(new Intent(con, SfSubActivity.class).putExtras(b).putExtra("type", "edit").putExtra("mainid", mainid));
            }
        });
        //姓名
        name = (EditText) findViewById(R.id.name);
        idno = (EditText) findViewById(R.id.idno);
        phone = (EditText) findViewById(R.id.phone);
        totalfy = (TextView) findViewById(R.id.totalfy);
        back = (LinearLayout) findViewById(R.id.back);
        zfll = (LinearLayout) findViewById(R.id.zfll);
        zfll.setVisibility(View.VISIBLE);
        mxadd = (TextView) findViewById(R.id.mxadd);

        title = (TextView) findViewById(R.id.title);
        saveBtn = (TextView) findViewById(R.id.uname);
        title.setText("收费新增");
        saveBtn.setText("保存");
        zhifu = (TextView)findViewById(R.id.zhifu);
    }
    @Override
    protected void initData() {
        if (getIntent().getStringExtra("type").equals("edit")) {
            isadd = false;
            obj = (AppSfMain) getIntent().getExtras().getSerializable("b");
            mainid = obj.getNid();
            init(obj);
        } else {
            isadd = true;//是否是新添加
            obj = new AppSfMain();
            init(obj);
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetWorkUtils.isNetworkConnected(con)) {//联网状态
            getInfo();
        } else {
            getInfoNoNet();
        }
    }

    private void getInfoNoNet(){
        list = LitePal.where("mainid = ?", mainid).order(" addtime asc").find(AppSfSub.class);
        listView.setAdapter(new CommonAdapter(con, list, R.layout.sf_sub_item) {
            @Override
            public void convert(ViewHolder helper, Object item) {
                if (item instanceof AppSfSub) {
                    AppSfSub appSfSubItem = (AppSfSub) item;
                    helper.setText(R.id.xmname, appSfSubItem.getXmname());
                    helper.setText(R.id.fy, appSfSubItem.getFy() + "");
                }
            }
        });
        LvHeightUtil.setListViewHeightBasedOnChildren(listView);
    }

    private void init(final AppSfMain obj) {
        if (obj != null && !StringUtils.isEmpty(obj.getName())) {
            name.setText(obj.getName());
        }

        if (obj != null && !StringUtils.isEmpty(obj.getIdno())) {
            idno.setText(obj.getIdno());
        }

        if (obj != null && !StringUtils.isEmpty(obj.getPhone())) {
            phone.setText(obj.getPhone());
        }

        if (obj != null && null != obj.getTotalfy()) {
            totalfy.setText(obj.getTotalfy() + "");
        }
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                startActivity(new Intent(con, SflistActivity.class));
            }
        });
        if (!isadd) {
            mxadd.setVisibility(View.VISIBLE);
        }
        mxadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(con, SfSubActivity.class).putExtra("type", "add").putExtra("mainid", mainid));
            }
        });
        zhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                Bundle b = new Bundle();
                b.putSerializable("b", getIntent().getExtras().getSerializable("b"));
                startActivity(new Intent(con, ZfChooseActivity.class).putExtras(b).putExtra("type", "edit"));
            }
        });
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //boolean validate = BinderUtil.copyDataToView(grjbxx_fh.this, obj);
                String nameText = name.getText().toString();
                String idnoText = idno.getText().toString();
                String phoneText = phone.getText().toString();
                String totalfyText = totalfy.getText().toString();
                if (null == nameText || "".equals(nameText)) {
                    MyToastUtil.ShowToast(con, "请输入姓名");
                } else if (null != nameText && !"".equals(nameText) && nameText.length() > 10) {
                    MyToastUtil.ShowToast(con, "请输入正确汉字姓名切不能超过10个字符");
                } else if (null == totalfyText || "".equals(totalfyText)) {
                    MyToastUtil.ShowToast(con, "请在下方输入明细信息");
                } else if (null != phoneText && !"".equals(phoneText) && !RegexUtils.isMobileExact(phoneText)) {
                    MyToastUtil.ShowToast(con, "请输入正确手机号码");
                } else if (null != idnoText && !"".equals(idnoText) && !RegexUtils.isIDCard18(idnoText)) {
                    MyToastUtil.ShowToast(con, "请输入正确身份证号码");
                } else {//验证通过
                    obj.setName(nameText);
                    obj.setIdno(idnoText);
                    obj.setPhone(phoneText);

                    if (NetWorkUtils.isNetworkConnected(con)) {
                        //网络连接时
                        RequestParams ps = new RequestParams();
                        if (isadd) {
                            url = HttpUrl.SaveSfmain;
                        } else {
                            ps.add("entity.NID", obj.getNid());
                            url = HttpUrl.EditSfmain;
                        }
                        ps.add("entity.NAME", nameText);
                        ps.add("entity.IDNO", idnoText);
                        ps.add("entity.PHONE", phoneText);
                        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                        ps.add("type", "2");

                        UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(String content) {
                                super.onSuccess(content);
                                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                                if (ret.getCode().equals("200")) {
                                    MyToastUtil.ShowToast(con, "成功");
                                    Bundle b = new Bundle();
                                    obj.setNid(ret.getRd());
                                    b.putSerializable("b", obj);
                                    finish();
                                    startActivity(new Intent(con, SfaddActivity.class).putExtras(b).putExtra("type", "edit").putExtra("mainid", mainid));
                                }
                            }

                            @Override
                            public void onFailure(Throwable error) {
                                super.onFailure(error);
                                saveOfNoNet();
                            }
                        });
                    }else{
                        saveOfNoNet();
                    }
                }
            }
        });
    }

    public void saveOfNoNet(){
        //网络不通,保存本地
        String nid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
        obj.setNid(nid);
        obj.setTbtime(DateConvert.getDateString(DateConvert.YMDHMS));
        obj.setTotalfy("0");
        obj.setYsid(SharedPreferencesUtils.getParam(con, "username", "").toString());
        obj.setYsname(SharedPreferencesUtils.getParam(con, "uname", "").toString());
        obj.setYsyljg(SharedPreferencesUtils.getParam(con, "yljg", "").toString());
        obj.setYsrybh(SharedPreferencesUtils.getParam(con, "rybh", "").toString());
        obj.save();
        Bundle b = new Bundle();
        b.putSerializable("b", obj);
        finish();
        startActivity(new Intent(con, SfaddActivity.class).putExtras(b).putExtra("type", "edit").putExtra("mainid", nid));
    }

    public void getInfo() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        ps.add("mainid", obj.getNid());
        UserClient.get(HttpUrl.GetSfsubList, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Throwable error, String content) {
                super.onFailure(statusCode, error, content);
                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<AppSfSub> ll = JSON.parseArray(ret.getList(), AppSfSub.class);
                    if (pageNum1 == 1)
                        list = new ArrayList<AppSfSub>();
                    for (int i = 0; i < ll.size(); i++) {
                        AppSfSub appSfSub = ll.get(i);
                        list.add(appSfSub);
                    }
                    listView.setAdapter(new CommonAdapter(con, list, R.layout.sf_sub_item) {
                        @Override
                        public void convert(ViewHolder helper, Object item) {
                            if (item instanceof AppSfSub) {
                                AppSfSub appSfSubItem = (AppSfSub) item;
                                helper.setText(R.id.xmname, appSfSubItem.getXmname());
                                helper.setText(R.id.fy, appSfSubItem.getFy() + "");
                            }
                        }
                    });
                    LvHeightUtil.setListViewHeightBasedOnChildren(listView);
                } else {
                    //MyToastUtil.ShowToast(con, "获取错误");
                    getInfoNoNet();
                }
            }
        });
    }
}
